import React, { useState, useEffect, useCallback } from 'react'
import { TreeSelect, Spin } from 'antd'
import { Category } from '@/pages/goods/category/data'
import { queryAllRule } from '@/pages/goods/category/service'
import { arrToTree } from '@/utils/utils'

export interface ICatrgoryProps {
    placeholder: string,
    value?: string
    onChange?: (key: string) => void
}

type TreeNodeDef = Category & {
    children?: TreeNodeDef[]
}
export const CategorySelect: React.FunctionComponent<ICatrgoryProps> = ({
    placeholder,
    value,
    onChange
}) => {
    const [categoryList, setCategoryList] = useState<Category[]>()

    useEffect(() => {
        queryAllRule().then(({ data, code }) => {
            if (code === 0) {
                setCategoryList(arrToTree(data))
            }
        });
    }, [])
    const onChangeHandler = useCallback((value: string) => {
        
        onChange?.(value)
    }, [])


    const renderNode = (categorys: TreeNodeDef[]) => {
        return (
            categorys.map((category) => (<TreeSelect.TreeNode
                value={+category.id} title={category.name}>
                {category.children && renderNode(category.children)}
            </TreeSelect.TreeNode>)
            )
        )
    }


    return (
        <Spin spinning={categoryList === null}>
            {
                categoryList &&
                <TreeSelect
                    placeholder={placeholder}
                    value={value}
                    onChange={onChangeHandler}
                    allowClear
                    showSearch
                    style={{ width: '100%' }}
                    dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                >
                    {renderNode(categoryList)}
                </TreeSelect>
            }
        </Spin>
    )
}
